package com.ty.reaml;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.ty.entity.SysAdmin;
import com.ty.service.AdminService;

//用户和权限验证的处理类
public class AuthReaml extends AuthorizingRealm {

	
	@Autowired
	private AdminService adminService;
	
	//角色和权限验证的方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//获取当前登录的用户信息
		SysAdmin sysAdmin=(SysAdmin)SecurityUtils.getSubject().getSession().getAttribute("user");
		
		//添加角色信息
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		//获取当前用户的权限
		//授权的角色信息，授权菜单权限
		Map<String,Object> bean= adminService.selectByUserAuth(sysAdmin);
		List<String> roles=(List<String>) bean.get("role");
//		roles.add("role1");
//		roles.add("role2");
		simpleAuthorizationInfo.addRoles(roles); //将当期的用户添加角色
		
		//添加授权权限
		List<String> pers=(List<String>) bean.get("menus");
//		pers.add("admin:index:index");
//		pers.add("admin:index:roles");
//		pers.add("admin:index:add");
		
		simpleAuthorizationInfo.addStringPermissions(pers);
		
		return simpleAuthorizationInfo;
	}

	//用户验证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//用户名称
		String username= (String) token.getPrincipal();
		//获取密码
		String password=new String((char[])token.getCredentials());
		
		SysAdmin sysAdmin= adminService.login(username,password);
		if(sysAdmin==null) { //判断用户名
			throw new AuthenticationException("用户名或密码错误"); //如果用户名错误
		}
	
		//获取shiro中的session对象
		SecurityUtils.getSubject().getSession().setAttribute("user",sysAdmin);
		//表示验证成功了
		return new SimpleAuthenticationInfo(username,password,getName());
	}

}
